<?php
/* 
    Name：FastPHP
    CopyRight: Mr.Fu 2019SR0832915
*/
namespace app\extend\weixin;
/*
	微信接口相关公共方法
*/
use \app\base\Common;

class Wxcommon extends Common
{
	protected function _initialize()
	{
    	//执行父类的构造方法
    	parent::_initialize();
	}
	//生成数据签名处理 SHA1
	static public function MakeSign_SHA1($arr)
	{
		ksort($arr);						//签名步骤一：按字典序排序参数
		$string =self::ToUrlParams($arr);
		$string = sha1($string);			//签名步骤三：sha1加密
		return $string;
	}
	//生成数据签名处理 MD5
	static public function MakeSign_MD5($arr,$KEY)
	{
		ksort($arr);						//签名步骤一：按字典序排序参数
		$string = self::ToUrlParams($arr);
		$string = $string . "&key=".$KEY;	//签名步骤二：在string后加入KEY
		$string = md5($string);				//签名步骤三：MD5加密
		$result = strtoupper($string);		//签名步骤四：所有字符转为大写
		return $result;
	}
	//格式化参数格式化成url参数
	static function ToUrlParams($arr)
	{
		$buff = "";
		foreach ($arr as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}
	//数组转换成Xml数据 
	static public function ToXml($arr)
	{
    	$xml = "<xml>";
    	foreach ($arr as $key=>$val){
    		if (is_numeric($val)){
    			$xml.="<".$key.">".$val."</".$key.">";
    		}else{
    			$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
    		}
        }
        $xml.="</xml>";
        return $xml; 
	}
	//以post方式提交xml到对应的接口url
	static public function postXmlCurl($xml, $url, $SSLCERT ="",$SSLKEY="")
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);					//设置超时
		curl_setopt($ch,CURLOPT_URL, $url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);			//严格校验
		curl_setopt($ch, CURLOPT_HEADER, FALSE);				//设置header
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);			//要求结果为字符串且输出到屏幕上
		//证书不为空开始设置证书
		if($SSLCERT !="" and $SSLKEY!=""){
			curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLCERT,$SSLCERT);
			curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLKEY,$SSLKEY);
		}
		curl_setopt($ch, CURLOPT_POST, TRUE);					//post提交方式
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
		$data = curl_exec($ch);									//运行curl
		if($data){
			curl_close($ch);
			return $data;
		} else { 
			$error = curl_errno($ch);
			curl_close($ch);
			WLog('WxCURL',"WxCURL出错，错误码:$error");
		}
	}  
}
?>